package LeetCode;


import java.util.Stack;

public class TreeNode {
     int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

class Solution {
    public boolean isValidBST(TreeNode root) {
        TreeNode p = root;
        Long tp = Long.MIN_VALUE;
        Stack<TreeNode> stack = new Stack<>();
        while(p != null || !stack.isEmpty()) {
            if(p != null) {
                stack.push(p);
                p = p.left;
            }else {
                TreeNode pop = stack.pop();
                if (tp >= pop.val) {
                    return false;
                }
                tp = (long)pop.val;
                p = pop.right;
            }
        }
        return true;
    }
}
